/* eslint-disable func-names */
import { takeLatest, takeEvery, put, call, fork } from "redux-saga/effects";
import { addApi, deleteApi, updateApi, fetchAllApi } from "@service/api";
import { notification } from "antd";
import intl from "react-intl-universal";
import messages from "@i18n/messages";
import { apiAction, errorAction } from "../actions";
import ACTION from "../constant/action-types";
import { safe } from "./utils";

function* addApiProvider(action) {
  const api = action.payload;
  const data = api.toJS();
  yield call(addApi, data);
  yield put(apiAction.add(api));
}

function* removeApiProvider(action) {
  const api = action.payload;
  yield call(deleteApi, api.id);
  yield put(apiAction.remove(api));
}

function* updateApiProvider(action) {
  const { id, api } = action.payload;
  const data = api.toJS();
  yield call(updateApi, { ...data, id });
  yield put(apiAction.update(id, api));
}

function* fetchApiProviderList() {
  const response = yield call(fetchAllApi);
  yield put(apiAction.setApiList(response.data));
}

function displayError(action) {
  const { error } = action;
  const errorAction = action.action;
  if(error.message !== '请上传license恢复使用'){
    notification.error({
      description: `${intl.get(messages.errorNotification.errorText.id)}: ${
        error.message
      }`,
      message: `${errorAction.type}`,
    });
  }
}

export default function* root() {
  yield takeLatest(ACTION.REQUSET_ADD_API_PROVIDER, safe(addApiProvider));
  yield takeLatest(ACTION.REQUEST_REMOVE_API_PROVIDER, safe(removeApiProvider));
  yield takeLatest(ACTION.REQUEST_UPDATE_API_PROVIDER, safe(updateApiProvider));
  yield takeEvery(ACTION.ERROR, displayError);
  yield fork(
    safe(fetchApiProviderList, "fetchApi", function*(error) {
      yield put(
        errorAction.error(error, {
          type: intl.get(messages.errorNotification.api.id),
        })
      );
    })
  );
}
